package chapter11_3_concurrentHashMap;

import cn.hutool.json.JSONUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 虽然是并发安全的组件,但是如果使用不当,仍会导致错误
 * @author Summerday
 */
public class TestMap {
    // key 为topic value 为设备列表
    static ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<>();


    public static void main(String[] args) {
        Thread threadOne = new Thread(()->{
           List<String> list1 = new ArrayList<>();
           list1.add("device1");
           list1.add("device2");
           map.put("topic1",list1);
            System.out.println(JSONUtil.toJsonStr(map));
        });

        Thread threadTwo = new Thread(()->{
            List<String> list1 = new ArrayList<>();
            list1.add("device11");
            list1.add("device22");
            map.put("topic1",list1);
            System.out.println(JSONUtil.toJsonStr(map));
        });

        Thread threadThree = new Thread(()->{
            List<String> list1 = new ArrayList<>();
            list1.add("device111");
            list1.add("device222");
            map.put("topic3",list1);
            System.out.println(JSONUtil.toJsonStr(map));
        });

        threadOne.start();
        threadTwo.start();
        threadThree.start();
    }

}
